package com.costeaalex.MIDlets.remote.threads;

import java.util.Vector;

import com.costeaalex.MIDlets.remote.canvas.CommandReceiver;
import com.costeaalex.MIDlets.remote.communication.CommunicationManager;

public class Receiver extends Thread
	{
	
	private CommunicationManager cML;
	private boolean isAlive=false;
	private Vector commReceivers=new Vector();
	private boolean receivingCommand=true;
	private byte[] command;
	/*private byte[] imgByteReadBuffer;
	private byte[] imgByteBuffer=new byte[50000];
	private byte[] imgByte;
	private int offset;
	private boolean receiveImages=false;*/
	
	public Receiver(CommunicationManager cM)
		{
		cML=cM;
		isAlive=true;
		}
	
	public void run()
		{
		
		while(isAlive)
			{
			if(receivingCommand)
				{
				if(cML.getAvailableData()!=0)
					{
					command=new byte[10];
					command=cML.receiveBlock();
					if(command!=null)
						dispatchCommand(command);
					}
				}
			
			/*if(receiveImages)
				{
				try
					{
					if(cML.getAvailableData()!=0)
						{
						imgByteReadBuffer=new byte[cML.getAvailableData()];
						imgByteReadBuffer=cML.receiveBlock();
						
						if(imgByteReadBuffer.length>1)
							{
							k=0;
							for(i=offset; i<offset+imgByteReadBuffer.length; i++)
								{
								imgByteBuffer[i]=imgByteReadBuffer[k];
								k++;
								}
							offset+=imgByteReadBuffer.length;
							cML.send(50);
							}
						else
							if(imgByteReadBuffer.length==1 && imgByteReadBuffer[0]==60)
								{
								imgByte=new byte[offset];
								for(i=0; i<offset; i++)
									imgByte[i]=imgByteBuffer[i];
								drawReceivedImage(imgByte);
								//cL.drawInt(imgByte.length);
								//try	{ sleep(5000); } catch (InterruptedException e)	{e.printStackTrace();}
								cML.send(50);
								
								offset=0;
								imgByteBuffer=new byte[50000];
								}
						}
					}
				catch(Exception e)
					{
					cML.send(51);
					offset=0;
					imgByteBuffer=new byte[50000];
					}
				}
			else //if not image receive
				{
				
				}*/
			}
		}
	
	private void dispatchCommand(byte[] command)
		{
		int i;
		for(i=0; i<commReceivers.size(); i++)
			if(((CommandReceiver) commReceivers.elementAt(i)).getReceiverId()==command[1])
				{
				((CommandReceiver) commReceivers.elementAt(i)).parseCommand(command);
				break;
				}
		}
	
	public void destroy()
		{
		isAlive=false;
		}
	
	public void addReceiver(CommandReceiver cR)
		{
		commReceivers.addElement(cR);
		}
	}
